import {defineStore, storeToRefs} from 'pinia';
import { computed, ref } from 'vue';
import {useFormStore} from "../stores/form";
import {merge}  from  'lodash-es'
import {flattenObject} from "../utils";

/**
 *
 * @param originColumns {[]} 初始化配置
 * @param initFn  {()=>Record<string,any>} 数据请求的方法
 * @param originOption?  {Object} formcreate全局配置
 */
export const useCreateForm =  (originColumns: Object[], initFn: () => Record<string, any>, originOption?: Object)=>{
    const formStore=useFormStore();
    const {formDate,columns,snapshotFormData}=storeToRefs(formStore)
    //默认全局配置
    const defaultOption={
        submitBtn: {
            show: false,
        },
        form: {
            required: "auto",
            inputAlign: "left",
            labelAlign: "top",
        },
    }
    //合并默认配置和外部来源的配置组合成最终配置 需要递归
      const option=  merge({},defaultOption,originOption)
    // debugger;
    //数据初始化 依托响应式完成数据更新
   initFn().then(res=>{
       formDate.value=res;
   });
    //初始化数据快照 用于重置
    snapshotFormData.value=flattenObject(formDate.value)
    //初始化列配置
    columns.value=originColumns;
    return {
        columns,
        formDate,
        option
    }
}
